﻿using ACS.SPiiPlusNET;
using Company.Hardware.Acs;
using Company.Share.Events;
using Company.UI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace Company.UI.ViewModels
{
    public class ConnectionControlViewModel : BindableBase
    {
        public AcsControllerProvider AcsControllerProvider { get; private set; }
        private IEventAggregator EventAggregator; // 事件聚合器
        public ConnectionControlModel ConnectionModel { get;private set; }
        public DelegateCommand AcsConnectionCommand { get;}
        public DelegateCommand SaveToFlashCommand { get;}
        public DelegateCommand ControllerRebootCommand { get;}
        public ConnectionControlViewModel(AcsControllerProvider acsControllerProvider, IEventAggregator eventAggregator)
        {
            AcsControllerProvider = acsControllerProvider;
            EventAggregator = eventAggregator;
            ConnectionModel = new ConnectionControlModel();
            AcsConnectionCommand = new DelegateCommand(AcsConnection);
            SaveToFlashCommand = new DelegateCommand(SaveToFlash);
            ControllerRebootCommand = new DelegateCommand(ControllerReboot);
        }
        /// <summary>
        /// 重启控制器
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ControllerReboot()
        {
            AcsControllerProvider.AcsController.ControllerReboot(50000);
        }
        /// <summary>
        /// 保存到Flash
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void SaveToFlash()
        {
            AcsControllerProvider.AcsController.SaveToFlash();
        }
        /// <summary>
        /// Acs连接/断开
        /// </summary>
        private void AcsConnection()
        {
            ConnectionModel.IsConnected = AcsControllerProvider.AcsController.IsConnected;
            if (ConnectionModel.IsConnected)
            {
                AcsControllerProvider.AcsController.Disconnect();
            }
            else
            {
                //TCP Ethernet连接
                AcsControllerProvider.AcsController.ConnectToEthernetTCP(ConnectionModel.IpAddress, ConnectionModel.Port);
            }
            ConnectionModel.IsConnected = AcsControllerProvider.AcsController.IsConnected;
            // 事件聚合器发布事件
            EventAggregator.GetEvent<AcsControllerConnectedEvent>().Publish(ConnectionModel.IsConnected);
        }
    }
}
